package com.xuxueli.applyModules.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Scanner;

/**
 * 账册日志
 * @Date 2021/1/5
 */
public class TextReaderLog {
    public static void main(String[] args) {
        String paramsCodes = "{\"Url\":\"127.0.0.1\",\"UrlName\":\"test\"}";
        JSONObject jsonObj = JSONObject.parseObject(paramsCodes);
        System.out.println("解析对象："+jsonObj+",解析字符串："+jsonObj.get("Url").toString());
        String pathfile = "D:\\整理账册错误日志\\ems\\ems-api_log_error.log";
        //gbk   utf-8
        //scanRead(pathfile,"utf-8");
        File file = new File("D:\\整理账册错误日志\\ems");
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file1 = files[i];
            if(file1.isFile()){
                if(file1.getName().contains("ems-api")){
                    readDataToFileApi(file1.getPath(),"utf-8","2021-01-21");
                }else if(file1.getName().contains("ems-import-executor")){
                    readDataToFileExecutor(file1.getPath(),"utf-8","2021-01-19");
                }else if(file1.getName().contains("ems-msg-rc")){
                    readDataToFileMsgRc(file1.getPath(),"utf-8","2021-01-21");
                }else if(file1.getName().contains("ems-msg-resolver")){
                    readDataToFileMsgRes(file1.getPath(),"utf-8","2021-01-21");
                }else if(file1.getName().contains("sync-service")){
                    readDataToFileSync(file1.getPath(),"utf-8","2021-01-21");
                }else{
                    System.out.println(file1.getName());
                }
            }
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    protected static void scanRead(String pathfile,String charsetName){
        try(Scanner scanner = new Scanner(new File(pathfile),charsetName)) {
            while (scanner.hasNextLine()) {
                String currentLine = scanner.nextLine();
                if(!currentLine.contains("未携带登录信息")) {
                    System.out.println(currentLine);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    public static void readDataToFileApi(String filePath,String charsetName,String selectDate){
        try {
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),charsetName);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if(lineTxt.contains(selectDate)){
                        lineTxt = lineTxt.replace(lineTxt,"sppace");
                    }
                    sb.append(lineTxt+"\n");
                }
                read.close();
                String string = sb.toString();
                String[] split = string.split("sppace");
                for (int i = 0; i < split.length; i++) {
                    if(!(split[i].contains("未携带登录信息") || split[i].contains("java.net.SocketTimeoutException"))){
                        if(StringUtils.isNotEmpty(split[i])) {
                            if(!"\n".equals(split[i]))
                                System.out.println("账册api:"+split[i]);
                        }
                    }
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    public static void readDataToFileExecutor(String filePath,String charsetName,String selectDate){
        try {
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),charsetName);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if(lineTxt.contains(selectDate)){
                        lineTxt = lineTxt.replace(lineTxt,"sppace");
                    }
                    sb.append(lineTxt+"\n");
                }
                read.close();
                String string = sb.toString();
                String[] split = string.split("sppace");
                for (int i = 0; i < split.length; i++) {
                    if(!(split[i].contains("java.net.SocketTimeoutException")
                            || split[i].contains("io.sentry.connection.ConnectionException"))){
                        if(StringUtils.isNotEmpty(split[i])) {
                            if(!"\n".equals(split[i]))
                                System.out.println("账册import:"+split[i]);
                        }
                    }
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    public static void readDataToFileMsgRc(String filePath,String charsetName,String selectDate){
        try {
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),charsetName);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if(lineTxt.contains(selectDate)){
                        lineTxt = lineTxt.replace(lineTxt,"sppace");
                    }
                    sb.append(lineTxt+"\n");
                }
                read.close();
                String string = sb.toString();
                String[] split = string.split("sppace");
                for (int i = 0; i < split.length; i++) {
                    if(!(split[i].contains("org.apache.kafka.clients.consumer.CommitFailedException")
                            || split[i].contains("java.net.SocketTimeoutException")
                            || split[i].contains("io.sentry.connection.ConnectionException")
                            || split[i].contains("org.springframework.kafka.listener.ListenerExecutionFailedException"))){
                        if(StringUtils.isNotEmpty(split[i])) {
                            if(!"\n".equals(split[i]))
                                System.out.println("账册msg-rc:"+split[i]);
                        }
                    }
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    public static void readDataToFileMsgRes(String filePath,String charsetName,String selectDate){
        try {
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),charsetName);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if(lineTxt.contains(selectDate)){
                        lineTxt = lineTxt.replace(lineTxt,"sppace");
                    }
                    sb.append(lineTxt+"\n");
                }
                read.close();
                String string = sb.toString();
                String[] split = string.split("sppace");
                for (int i = 0; i < split.length; i++) {
                    if(!(split[i].contains("org.springframework.kafka.listener.ListenerExecutionFailedException"))){
                        if(StringUtils.isNotEmpty(split[i])) {
                            if(!"\n".equals(split[i]))
                                System.out.println("账册msg-resolver:"+split[i]);
                        }
                    }
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    public static void readDataToFilePublicSer(String filePath,String charsetName,String selectDate){
        try {
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),charsetName);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if(lineTxt.contains(selectDate)){
                        lineTxt = lineTxt.replace(lineTxt,"sppace");
                    }
                    sb.append(lineTxt+"\n");
                }
                read.close();
                String string = sb.toString();
                String[] split = string.split("sppace");
                for (int i = 0; i < split.length; i++) {
                    if(!(split[i].contains("org.apache.kafka.clients.consumer.CommitFailedException")
                            || split[i].contains("java.net.SocketTimeoutException")
                            || split[i].contains("io.sentry.connection.ConnectionException"))){
                        if(StringUtils.isNotEmpty(split[i])) {
                            if(!"\n".equals(split[i]))
                                System.out.println("账册public-service:"+split[i]);
                        }
                    }
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /**
     * 读取文件中的数据
     * @throws IOException
     */
    public static void readDataToFileSync(String filePath,String charsetName,String selectDate){
        try {
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),charsetName);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                StringBuilder sb = new StringBuilder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if(lineTxt.contains(selectDate)){
                        lineTxt = lineTxt.replace(lineTxt,"sppace");
                    }
                    sb.append(lineTxt+"\n");
                }
                read.close();
                String string = sb.toString();
                String[] split = string.split("sppace");
                for (int i = 0; i < split.length; i++) {
                    if(!split[i].contains("org.postgresql.util.PSQLException: FATAL: password authentication failed")){
                        if(StringUtils.isNotEmpty(split[i])) {
                            if(!"\n".equals(split[i]))
                                System.out.println("账册sync-excuter:"+split[i]);
                        }
                    }
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /**
     * 将格式化的数据写入文件中
     * @throws IOException
     */
    public static void writeDataToFile(String filePath,String charsetName) throws IOException {
        BufferedWriter bw = null;
        try {
            File file = new File(filePath);
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charsetName));
            for (int i=1; i<12; ++i) {
                bw.write(i);  // 将数据写入文件中
                bw.newLine();        // 新建一个换行符
                bw.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                bw.close();
            }
        }
    }

    /**
     * 功能描述:获取用户ip
     *@param request http请求
     *
     */
    public String getIpAddr(HttpServletRequest request) {
        String host = request.getHeader("host") + request.getRequestURI();
        System.out.println(host);
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        System.out.println("获取客户端ip: " + ip);
        return ip;
    }

}